import type {
    InputOption,
    InputPluginOption,
    OutputOptions,
    OutputPluginOption,
    RollupOptions, //
    GlobalsOption,
} from "rollup";

import { BundleFormat } from "./BundleFormat";
import { getPreferenceOption, type PreferenceOption } from "./PreferenceOption";
import { getOutputCommon } from "./internal/outputCommon";

/**
 * 根据偏好选项 <@see {@link PreferenceOption}> 格式化单入口模块文件名
 * - option.outDir
 * - option.bundleBaseName
 * @param formating 输出模块格式 <@see {@link BundleFormat}>
 * @returns 格式化后的单文件名
 * @example
 * - option.outDir = "dist"
 * - option.bundleBaseName = "index"
 * - formating = BundleFormat.ESM
 * - the Result will be "dist/index.esm.js"
 */
function _singleChunkFormattingFile(formating: BundleFormat) {
    const { outDir, bundleBaseName } = getPreferenceOption();
    const result = `${outDir}/${bundleBaseName}.${formating.toString().toLowerCase()}.js`;
    return result;
}

/**
 * 生成 OutputOptions
 * @param filePath 格式化过的输出文件全路径
 * @param formatting 工具包格式
 * @param minify 压缩插件
 * @returns
 */
function _singleOutputOptions(filePath: string, formatting: BundleFormat, minify?: OutputPluginOption) {
    const outputCommon = getOutputCommon();
    const { globals, banner, footer } = getPreferenceOption();

    const _output: OutputOptions = {
        ...outputCommon,
        file: filePath,
        format: `${formatting}`,
        name: `${formatting}.namespace`,
        globals: globals,
        banner: banner,
        footer: footer,
    };

    if (minify) {
        _output.plugins = minify; // 压缩代码
    }

    return _output;
}

/**
 * 单模块输入
 * @param inputs
 */
function singleChunkInputs(inputs: string) {
    return inputs as InputOption;
}

/**
 *
 * @param formatting
 * @param minify
 * @returns
 */
function singleChunkOutputs(formatting: BundleFormat, minify?: OutputPluginOption) {
    const _filePath = _singleChunkFormattingFile(formatting);
    const _output = _singleOutputOptions(_filePath, formatting, minify);
    return _output;
}

/**
 *
 * @param fileName
 * @param formatting
 * @param minify
 * @returns
 */
function singleChunkOutputsByFilename(fileName: string, formatting: BundleFormat, minify?: OutputPluginOption) {
    const { outDir } = getPreferenceOption();
    const _filePath = `${outDir}/${fileName}`;
    const _output = _singleOutputOptions(_filePath, formatting, minify);
    return _output;
}

export { singleChunkInputs, singleChunkOutputs, singleChunkOutputsByFilename };
